<template>
  <el-dialog
    :title="shareData.title"
    :visible.sync="shareData.isShow"
    width="75%"
    modal
    center
    top="5vh"
    :before-close="close"
    :show-close="true"
  >
    <el-form ref="modalRef" :model="modalForm" :rules="rules" label-width="140px">
      <el-row>
        <el-col :span="12">
          <el-form-item label="名称：" prop="alarmPlanName">
            <el-input v-model="modalForm.alarmPlanName" :disabled="shareData.isDisable" placeholder="请输入名称" size="small"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="描述：">
            <el-input v-model="modalForm.memo" :disabled="shareData.isDisable" placeholder="请输入名称" size="small"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="设备类型：" prop="eqptTypeId">
            <el-select
              placeholder="请选择设备类型"
              filterable clearable
              v-model="modalForm.eqptTypeId"
              :disabled="shareData.isDisable"
              size="small" style="width: 100%"
              @change="handleEqptType">
              <el-option
                v-for="item in eqptTypeList"
                :key="item.typeId"
                :label="item.typeName"
                :value="item.typeId"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="告警设备：" prop="alarmEqptList">
            <el-select
              placeholder="请选择告警设备"
              filterable
              clearable
              multiple
              collapse-tags
              v-model="modalForm.alarmEqptList"
              size="small"
              style="width: 100%"
            >
              <el-option
                v-for="item in alarmEqptList"
                :key="item.eqptId"
                :label="`${item.eqptName} - ${item.areaName}`"
                :value="item.eqptId"
                :disabled="shareData.isDisable"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="告警策略状态：" prop="alarmPlanStatus">
            <el-select placeholder="请选择告警策略状态" filterable v-model="modalForm.alarmPlanStatus" :disabled="shareData.isDisable" size="small" style="width: 100%">
              <el-option
                v-for="item in alarmStatusList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12"></el-col>
        <el-col :span="24">
          <el-tabs>
            <el-tab-pane label="初级">
              <el-form-item label="告警策略等级：">
                <el-select placeholder="请选择告警策略等级" clearable v-model="alarmJunior" :disabled="shareData.isDisable" size="small" @change="handleAlarmGrade('初级')">
                  <el-option label="初级" :value="0" />
                </el-select>
              </el-form-item>
              <condition-form
               ref="juniorRef"
               v-if="alarmJunior === 0"
               v-model="juniorOption"
               :style="juniorOption.deleteFlag && juniorOption.deleteFlag === 1 ? {display: 'none'} : {display: 'block'}"
               :conditionMonitorList="conditionMonitorList"
               :actionMonitorList="actionMonitorList"
               :contentTemplateEqptNo="contentTemplateEqptNo"
               :contentTemplateEqptType="contentTemplateEqptType"
               :alarmEqptList="alarmEqptList"
               :eqptTypeId="modalForm.eqptTypeId"
               :eqptTypeList="eqptTypeList"
               :allAlarmEqptList="allAlarmEqptList"
               :workTypeList="workTypeList"
              />
            </el-tab-pane>
            <el-tab-pane label="中级">
              <el-form-item label="告警策略等级：">
                <el-select placeholder="请选择告警策略等级" clearable v-model="alarmMiddle" :disabled="shareData.isDisable" size="small" @change="handleAlarmGrade('中级')">
                  <el-option label="中级" :value="1" />
                </el-select>
              </el-form-item>
              <condition-form
                ref="middleRef"
                v-if="alarmMiddle"
                v-model="middleOption"
                :style="middleOption.deleteFlag && middleOption.deleteFlag === 1 ? {display: 'none'} : {display: 'block'}"
                :conditionMonitorList="conditionMonitorList"
                :actionMonitorList="actionMonitorList"
                :contentTemplateEqptNo="contentTemplateEqptNo"
                :contentTemplateEqptType="contentTemplateEqptType"
                :alarmEqptList="alarmEqptList"
                :eqptTypeId="modalForm.eqptTypeId"
                :eqptTypeList="eqptTypeList"
                :allAlarmEqptList="allAlarmEqptList"
                :workTypeList="workTypeList"
              />
            </el-tab-pane>
            <el-tab-pane label="高级">
              <el-form-item label="告警策略等级：">
                <el-select placeholder="请选择告警策略等级" clearable v-model="alarmHigh" :disabled="shareData.isDisable" size="small" @change="handleAlarmGrade('高级')">
                  <el-option label="高级" :value="2" />
                </el-select>
              </el-form-item>
              <condition-form
                ref="highRef"
                v-if="alarmHigh"
                v-model="highOption"
                :style="highOption.deleteFlag && highOption.deleteFlag === 1 ? {display: 'none'} : {display: 'block'}"
                :conditionMonitorList="conditionMonitorList"
                :actionMonitorList="actionMonitorList"
                :contentTemplateEqptNo="contentTemplateEqptNo"
                :contentTemplateEqptType="contentTemplateEqptType"
                :alarmEqptList="alarmEqptList"
                :eqptTypeId="modalForm.eqptTypeId"
                :eqptTypeList="eqptTypeList"
                :allAlarmEqptList="allAlarmEqptList"
                :workTypeList="workTypeList"
              />
            </el-tab-pane>
          </el-tabs>
        </el-col>
      </el-row>
    </el-form>
    <div class="footer">
      <el-button type="default" @click.native.prevent="close()">取消</el-button>
      <el-button v-if="!shareData.isDisable" type="primary" @click.native.prevent="save()">保存</el-button>
    </div>
  </el-dialog>
</template>
<script>
import { USER_INFO } from '@/views/children/workOrder/js/constants'
import ConditionForm from './strategy/ConditionForm'
import { getMonitorList, getEqptDataList, getWorkTypeList } from '../js/alarmStrategy'
// 校验规则
const rules = {
  alarmPlanName: [{ required: true, message: '请输入名称', trigger: 'blur' }],
  alarmPlanStatus: [{ required: true, message: '请选择告警策略状态', trigger: 'change' }],
  eqptTypeId: [{ required: true, message: '请选择设备类型', trigger: 'change' }],
  alarmEqptList: [{ required: true, message: '请选择告警设备', trigger: 'change' }]
}
export default {
  components: { ConditionForm },
  inject: ['shareData'],
  props: {
    eqptTypeList: {
      type: Array,
      default: () => ([])
    },
    alarmObj: {
      type: Object,
      default: () => ({})
    }
  },
  watch: {
    alarmObj: {
      deep: true,
      handler () {
        if (this.oneWatch) {
          this.modalForm = { ...this.modalForm, ...this.alarmObj }
          this.setModalFormParams(this.modalForm)
        }
      }
    },
    'modalForm.eqptTypeId': {
      immediate: true,
      handler () {
        if (this.modalForm.eqptTypeId) {
          this.handleContentTemplateEqptType(this.modalForm.eqptTypeId)
          this.getMonitorList(this.modalForm.eqptTypeId)
          this.getEqptDataList([this.modalForm.eqptTypeId]).then(() => {
            if (this.modalForm.alarmEqptList?.length) {
              this.contentTemplateEqptNo = this.handleContentTemplateEqptNo(this.modalForm.alarmEqptList)
            }
          })
          this.oneWatch = false
        }
      }
    },
    'modalForm.alarmEqptList': {
      immediate: true,
      deep: true,
      handler () {
        // 设置入参所需的参数格式
        if (this.shareData.title === '编辑自定义告警') {
          if (!this.modalForm.alarmEqptList.length && this.modalForm.alarmPlanEqptList?.length) {
            this.modalForm.alarmPlanEqptList.forEach(n => { n.deleteFlag = 1 })
            this.resetAlarmPlanEqptList = this.modalForm.alarmPlanEqptList
          } else if (this.modalForm?.alarmEqptList?.length && this.modalForm.alarmPlanEqptList?.length) {
            this.modalForm.alarmPlanEqptList.forEach(n => {
              if (!this.modalForm.alarmEqptList.includes(n.eqptId) && n.id && n.deleteFlag === 0) {
                n.deleteFlag = 1
              }
            })
            this.resetAlarmPlanEqptList = this.modalForm.alarmPlanEqptList
          }
        }
        if (this.modalForm.alarmEqptList?.length) {
          this.contentTemplateEqptNo = this.handleContentTemplateEqptNo(this.modalForm.alarmEqptList)
        }
        this.alarmPlanEqptList = [...this.resetAlarmPlanEqptList, ...this.setAlarmPlanEqptData(this.modalForm.alarmEqptList)]
      }
    }
  },
  data () {
    return {
      rules,
      alarmStatusList: [
        { label: '启用', value: 1 },
        { label: '停用', value: 0 }
      ],
      oneWatch: true, // 监听一次
      tempEqptTypeName: null, // 设备类型名称
      tempEqptName: [], // 设备名称
      conditionMonitorList: [],
      actionMonitorList: [],
      alarmEqptList: [],
      modalForm: {
        alarmPlanName: null,
        memo: null,
        eqptTypeId: null,
        alarmEqptList: [],
        alarmPlanStatus: 1,
        alarmPlanDetailList: []
      },
      triggerTimeObj: {}, // 触发时间数据集合
      alarmPlanEqptList: [], // 告警设备入参数据结构
      resetAlarmPlanEqptList: [],
      juniorOption: {},
      middleOption: {},
      highOption: {},
      alarmJunior: null, // 初级告警等级
      alarmMiddle: null, // 中级告警等级
      alarmHigh: null, // 高级告警等级
      alarmPlanDetailJuniorList: [],
      alarmPlanDetailMiddleList: [],
      alarmPlanDetailHighList: [],
      contentTemplateEqptNo: '',
      contentTemplateEqptType: '',
      juniorValidateFlag: false,
      middleValidateFlag: false,
      highValidateFlag: false,
      workTypeList: [],
      allAlarmEqptList: [] // 获取全部告警设备
    }
  },
  computed: {},
  methods: {
    save () {
      // 保存表单信息
      this.$refs['modalRef'].validate((valid) => {
        if (valid) {
          // 校验告警策略等级必须选择一个
          if (this.alarmJunior !== 0 && !this.alarmMiddle && !this.alarmHigh) {
            this.$message.warning('告警策略等级必须选择一个！')
            return false
          }
          if (this.alarmJunior === 0) {
            // 选中告警等级 - 告警等级初级触发条件校验
            this.alarmTriggerConditionValidate(this.$refs.juniorRef.$refs, this.juniorOption, 0)
          }
          if (this.alarmMiddle === 1) {
            // 选中告警等级 - 告警等级中级触发条件校验
            this.alarmTriggerConditionValidate(this.$refs.middleRef.$refs, this.middleOption, 1)
          }
          if (this.alarmHigh === 2) {
            // 选中告警等级 - 告警等级高级触发条件校验
            this.alarmTriggerConditionValidate(this.$refs.highRef.$refs, this.highOption, 2)
          }
        } else {
          return false
        }
      })
    },
    alarmTriggerConditionValidate (domRef, optionObj, alarmLevel) {
      // 告警触发条件校验
      domRef.conditionRef.$refs.conditionForm.validate((valid) => {
        this.setValidateSuccess(valid, alarmLevel)
        if (valid) {
          // 校验成功
          this.alarmGradeFormValidate(domRef, optionObj, alarmLevel)
        } else {
          return false
        }
      })
    },
    alarmGradeFormValidate (domRef, optionObj, alarmLevel) {
      // 告警匹配条件、触发条件校验
      domRef.gradeForm.validate((valid) => {
        this.setValidateSuccess(valid, alarmLevel)
        if (valid) {
          // 校验成功
          this.alarmTriggerTimeValidate(domRef, optionObj, alarmLevel)
        } else {
          return false
        }
      })
    },
    alarmTriggerTimeValidate (domRef, optionObj, alarmLevel) {
      // 告警触发时间校验
      domRef.triggerTimeRef.$refs.triggerTimeFormRef.validate((valid) => {
        this.setValidateSuccess(valid, alarmLevel)
        if (valid) {
          // 校验成功
          this.alarmTriggerActionValidate(domRef, optionObj, alarmLevel)
        } else {
          return false
        }
      })
    },
    alarmTriggerActionValidate (domRef, optionObj, alarmLevel) {
      // 告警触发动作校验
      domRef.triggerActionRef.$refs.triggerActionFormRef.validate((valid) => {
        this.setValidateSuccess(valid, alarmLevel)
        if (valid) {
          // 校验成功
          this.alarmLinkageActionValidate(domRef, optionObj, alarmLevel)
        } else {
          return false
        }
      })
    },
    alarmLinkageActionValidate (domRef, optionObj, alarmLevel) {
      // 告警联动动作校验
      domRef.actionRef.$refs.conditionForm.validate((valid) => {
        this.setValidateSuccess(valid, alarmLevel)
        if (valid) {
          // 校验成功
          this.handleAlarmParams()
          this.setTriggerTimeParams(optionObj)
          if (alarmLevel === 0) {
            this.alarmPlanDetailJuniorList = this.setConditionActionList(optionObj, alarmLevel)
          } else if (alarmLevel === 1) {
            this.alarmPlanDetailMiddleList = this.setConditionActionList(optionObj, alarmLevel)
          } else {
            this.alarmPlanDetailHighList = this.setConditionActionList(optionObj, alarmLevel)
          }
          this.modalForm.alarmPlanDetailList = [...this.alarmPlanDetailJuniorList, ...this.alarmPlanDetailMiddleList, ...this.alarmPlanDetailHighList]
          if (this.alarmJunior === 0 && this.alarmMiddle === 1 && this.alarmHigh === 2) {
            // 勾选初级、中级、高级
            if (!this.juniorValidateFlag || !this.middleValidateFlag || !this.highValidateFlag) {
              return false
            }
            this.$emit('ok', this.modalForm)
          } else if (this.alarmJunior === 0 && this.alarmMiddle === 1) {
            // 勾选初级和中级
            if (!this.juniorValidateFlag || !this.middleValidateFlag) {
              return false
            }
            this.$emit('ok', this.modalForm)
          } else if (this.alarmJunior === 0 && this.alarmHigh === 2) {
            // 勾选初级和高级
            if (!this.juniorValidateFlag || !this.highValidateFlag) {
              return false
            }
            this.$emit('ok', this.modalForm)
          } else if (this.alarmMiddle === 1 && this.alarmHigh === 2) {
            // 勾选中级和高级
            if (!this.middleValidateFlag || !this.highValidateFlag) {
              return false
            }
            this.$emit('ok', this.modalForm)
          } else if (this.alarmJunior === 0) {
            // 只勾选初级
            if (!this.juniorValidateFlag) {
              return false
            }
            this.$emit('ok', this.modalForm)
          } else if (this.alarmMiddle === 1) {
            // 只勾选中级
            if (!this.middleValidateFlag) {
              return false
            }
            this.$emit('ok', this.modalForm)
          } else if (this.alarmHigh === 2) {
            // 只勾选高级
            if (!this.highValidateFlag) {
              return false
            }
            this.$emit('ok', this.modalForm)
          }
        } else {
          return false
        }
      })
    },
    setValidateSuccess (flag, level) {
      // 告警初级，中级，告警校验成功标志
      if (level === 0) {
        this.juniorValidateFlag = flag
      } else if (level === 1) {
        this.middleValidateFlag = flag
      } else if (level === 2) {
        this.highValidateFlag = flag
      }
    },
    close () {
      // 关闭modal
      this.$emit('close', false)
    },
    handleEqptType () {
      // 切换设备类型清空
      this.resetEqptAssociatedFields()
    },
    resetEqptAssociatedFields () {
      if (this.shareData.title === '编辑自定义告警') {
        // 重置相关字段
        this.modalForm.alarmEqptList = []
        this.alarmEqptList = []
        this.resetAlarmPlanEqptList = this.modalForm.alarmPlanEqptList.map(n => {
          if (this.modalForm.eqptTypeId !== n.eqptTypeId) {
            return {
              deleteFlag: 1,
              id: n.id,
              eqptId: n.eqptId,
              eqptName: n.eqptName,
              eqptTypeId: n.eqptTypeId,
              sourceId: n.sourceId
            }
          }
        })
        this.conditionMonitorList = []
        this.actionMonitorList = []
      } else {
        this.modalForm.alarmEqptList = []
        this.alarmPlanEqptList = []
        this.conditionMonitorList = []
        this.actionMonitorList = []
      }
    },
    handleAlarmGrade (type) {
      // 删除deleteFlag字段处理
      if (type === '初级') {
        // 告警等级初级
        if (this.alarmJunior !== 0 && !this.modalForm.id) this.alarmPlanDetailJuniorList = []
        if (this.alarmJunior !== 0 && this.modalForm.id) {
          this.oneWatch = false
          const { alarmPlanDetailList } = this.modalForm
          alarmPlanDetailList.forEach(n => {
            if (n.id && n.alarmLevel === 0 && n.deleteFlag === 0) {
              n.deleteFlag = 1
              this.alarmPlanDetailJuniorList = [...this.alarmPlanDetailJuniorList, ...this.setConditionActionList(n, 0)]
              this.juniorOption = {}
            }
          })
        } else if (this.alarmJunior === 0 && this.modalForm.id) {
          this.oneWatch = false
          if (this.alarmPlanDetailJuniorList?.length) {
            this.alarmPlanDetailJuniorList = this.alarmPlanDetailJuniorList.filter(n => n.id)
            this.juniorOption = {}
          }
        }
      } else if (type === '中级') {
        // 告警等级初级
        if (this.alarmMiddle !== 1 && !this.modalForm.id) this.alarmPlanDetailMiddleList = []
        if (this.alarmMiddle !== 1 && this.modalForm.id) {
          this.oneWatch = false
          const { alarmPlanDetailList } = this.modalForm
          alarmPlanDetailList.forEach(n => {
            if (n.id && n.alarmLevel === 1 && n.deleteFlag === 0) {
              n.deleteFlag = 1
              this.alarmPlanDetailMiddleList = [...this.alarmPlanDetailMiddleList, ...this.setConditionActionList(n, 1)]
              this.middleOption = {}
            }
          })
        } else if (this.alarmMiddle === 1 && this.modalForm.id) {
          this.oneWatch = false
          if (this.alarmPlanDetailMiddleList?.length) {
            this.alarmPlanDetailMiddleList = this.alarmPlanDetailMiddleList.filter(n => n.id)
            this.middleOption = {}
          }
        }
      } else if (type === '高级') {
        // 告警等级初级
        if (this.alarmHigh !== 2 && !this.modalForm.id) this.alarmPlanDetailHighList = []
        if (this.alarmHigh !== 2 && this.modalForm.id) {
          this.oneWatch = false
          const { alarmPlanDetailList } = this.modalForm
          alarmPlanDetailList.forEach(n => {
            if (n.id && n.alarmLevel === 2 && n.deleteFlag === 0) {
              n.deleteFlag = 1
              this.alarmPlanDetailHighList = [...this.alarmPlanDetailHighList, ...this.setConditionActionList(n, 2)]
              this.highOption = {}
            }
          })
        } else if (this.alarmHigh === 2 && this.modalForm.id) {
          this.oneWatch = false
          if (this.alarmPlanDetailHighList?.length) {
            this.alarmPlanDetailHighList = this.alarmPlanDetailHighList.filter(n => n.id)
            this.highOption = {}
          }
        }
      }
    },
    async getMonitorList (eqptTypeId) {
      // 获取设备类型下拉数据
      try {
        const res = await getMonitorList({
          eqptTypeId,
          eqptTypeName: null,
          messageType: 0,
          pageNum: 1,
          pageSize: 10,
          tenantName: null,
          tenantNo: null
        })
        if (res.code === 0) {
          if (!res?.data?.recieveParamList?.length) {
            this.$confirm('该设备类型下触发条件监测属性下拉暂无数据，请联系管理员进行配置！', '温馨提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              this.resetEqptAssociatedFields()
            }).catch(() => {
              this.resetEqptAssociatedFields()
            })
            return false
          }
          this.conditionMonitorList = res.data.recieveParamList
          this.actionMonitorList = res.data.sendParamList.filter(n => n.showFlag === 1)
          return {
            conditionMonitorList: this.conditionMonitorList,
            actionMonitorList: this.actionMonitorList
          }
        }
      } catch (e) {}
    },
    async getEqptDataList (eqptTypsIds) {
      // 获取告警设备下拉数据
      try {
        const res = await getEqptDataList({
          eqptTypsIds
        })
        if (res.code === 0) {
          this.alarmEqptList = res.data
        }
      } catch (e) {}
    },
    async getAllAlarmEqptList () {
      // 获取全量的告警设备下拉数据为告警联动动作下指定设备时告警设备所需下拉数据
      try {
        const res = await getEqptDataList({
          eqptTypsIds: []
        })
        if (res.code === 0) {
          this.allAlarmEqptList = res.data
        }
      } catch (e) {}
    },
    handleContentTemplateEqptType (eqptTypeId) {
      // 告警消息模板 - 设备类型
      this.contentTemplateEqptType = this.eqptTypeList.find(n => n.typeId === eqptTypeId).typeName
    },
    handleContentTemplateEqptNo (eqptNoList) {
      // 告警消息 - 告警设备
      const eqptNo = []
      eqptNoList.forEach(n => {
        this.setAlarmPlanEqptData(this.modalForm.alarmEqptList).forEach(e => {
          if (n === e.eqptId) {
            eqptNo.push(e.sourceId)
          }
        })
      })
      return eqptNo.join(',')
    },
    setModalFormParams (params) {
      // 处理查看或编辑数据转换成页面所需格式
      this.oneWatch = false
      const { alarmPlanEqptList, alarmPlanDetailList, eqptTypeId } = params
      this.modalForm.alarmEqptList = alarmPlanEqptList.map(n => n.eqptId)
      this.modalForm.alarmPlanEqptList = alarmPlanEqptList
      this.getMonitorList(eqptTypeId).then(res => {
        const { conditionMonitorList, actionMonitorList } = res
        alarmPlanDetailList.forEach(n => {
          if (n.alarmLevel === 0) {
            const {
              id,
              alarmPlanConditionList,
              alarmPlanTrigActionList
            } = n
            this.alarmJunior = n.alarmLevel
            this.juniorOption = n
            this.juniorOption.id = id
            this.juniorOption.conditionMonitorList = conditionMonitorList
            this.juniorOption.actionMonitorList = actionMonitorList
            this.juniorOption.triggerTime = { ...this.setPageTriggerTimePageParams(n) }
            this.juniorOption.conditionObj = { ...this.setPageConditionActionList('告警触发条件', alarmPlanConditionList, conditionMonitorList) }
            this.juniorOption.actionObj = { ...this.setPageConditionActionList('告警联动动作', alarmPlanTrigActionList, actionMonitorList) }
            this.juniorOption.triggerAction = { ...this.setPageWorkOrderPageParams(n) }
          } else if (n.alarmLevel === 1) {
            const {
              id,
              alarmPlanConditionList,
              alarmPlanTrigActionList
            } = n
            this.alarmMiddle = n.alarmLevel
            this.middleOption = n
            this.middleOption.id = id
            this.middleOption.conditionMonitorList = conditionMonitorList
            this.middleOption.actionMonitorList = actionMonitorList
            this.middleOption.triggerTime = { ...this.setPageTriggerTimePageParams(n) }
            this.middleOption.conditionObj = { ...this.setPageConditionActionList('告警触发条件', alarmPlanConditionList, conditionMonitorList) }
            this.middleOption.actionObj = { ...this.setPageConditionActionList('告警联动动作', alarmPlanTrigActionList, actionMonitorList) }
            this.middleOption.triggerAction = { ...this.setPageWorkOrderPageParams(n) }
          } else if (n.alarmLevel === 2) {
            const {
              id,
              alarmPlanConditionList,
              alarmPlanTrigActionList
            } = n
            this.alarmHigh = n.alarmLevel
            this.highOption = n
            this.highOption.id = id
            this.highOption.conditionMonitorList = conditionMonitorList
            this.highOption.actionMonitorList = actionMonitorList
            this.highOption.triggerTime = { ...this.setPageTriggerTimePageParams(n) }
            this.highOption.conditionObj = { ...this.setPageConditionActionList('告警触发条件', alarmPlanConditionList, conditionMonitorList) }
            this.highOption.actionObj = { ...this.setPageConditionActionList('告警联动动作', alarmPlanTrigActionList, actionMonitorList) }
            this.highOption.triggerAction = { ...this.setPageWorkOrderPageParams(n) }
          }
        })
      })
    },
    setPageTriggerTimePageParams (params) {
      // 处理触发时间页面所需参数
      const { triggerPeriodType, triggerAssignDate, triggerTimeType, triggerTimeValues, triggerStartDate, triggerEndDate, triggerEndDateType } = params
      let timeValues = []
      let assignDate = {
        triggerAssignDate: ''
      }
      const timeType = {
        triggerTimeType
      }
      const timePointValues = {
        triggerTimePointValues: [{ timeValue: '09:00' }]
      }
      const timeRangeValues = {
        triggerTimeRangeValues: [{ timeValue: ['09:00', '18:00'] }]
      }
      if (triggerTimeType === 0) {
        // 时间点
        timeValues = triggerTimeValues.includes(',') ? triggerTimeValues.split(',') : [triggerTimeValues]
        timePointValues.triggerTimePointValues = timeValues.map(n => ({
          timeValue: n
        }))
      } else {
        // 时间段
        timeValues = triggerTimeValues.includes(',') ? triggerTimeValues.split(',') : [triggerTimeValues]
        timeRangeValues.triggerTimeRangeValues = timeValues.map(n => ({
          timeValue: n.split('~')
        }))
      }
      if (triggerPeriodType === 0) {
        // 单次上送参数
        assignDate.triggerAssignDate = triggerAssignDate
      } else if (triggerPeriodType === 1) {
        // 每天
        assignDate = {
          ...this.setPageTimeCommonParams(triggerEndDateType, triggerStartDate, triggerEndDate)
        }
      } else if (triggerPeriodType === 2) {
        // 每周
        assignDate = {
          triggerWeekAssignDate: triggerAssignDate?.length ? triggerAssignDate.split(',').map(n => Number(n)) : [],
          ...this.setPageTimeCommonParams(triggerEndDateType, triggerStartDate, triggerEndDate)
        }
      } else if (triggerPeriodType === 3) {
        // 每月
        assignDate = {
          triggerMonthAssignDate: triggerAssignDate?.length ? triggerAssignDate.split(',').map(n => Number(n)) : [],
          ...this.setPageTimeCommonParams(triggerEndDateType, triggerStartDate, triggerEndDate)
        }
      }
      if (triggerTimeType === 0) {
        return {
          ...timeType,
          ...timePointValues,
          ...assignDate
        }
      } else {
        return {
          ...timeType,
          ...timeRangeValues,
          ...assignDate
        }
      }
    },
    setPageTimeCommonParams (triggerEndDateType, triggerStartDate, triggerEndDate) {
      return {
        triggerEndDateType,
        triggerStartDate,
        triggerEndDate
      }
    },
    setPageConditionActionList (type, data, monitorList) {
      // 处理页面显示所需格式
      if (type === '告警触发条件') {
        const newData = data.map(n => ({
          selectFirstValue: n.eqptMessageParamId,
          selectSecondValue: n.alarmConditionId,
          selectThirdValue: n.threshold,
          propList: [],
          id: n.id,
          deleteFlag: n.deleteFlag
        }))
        if (monitorList?.length) {
          newData.map(n => {
            monitorList.forEach(c => {
              if (n.selectFirstValue === c.id && c.propList?.length) {
                n.propList = c.propList
                n.selectThirdValue = Number(n.selectThirdValue)
              }
            })
          })
          return {
            alarmConditionActionList: newData,
            conditionMonitorList: monitorList
          }
        }
      } else if (type === '告警联动动作') {
        if (data?.length) {
          const newData = data.map(n => ({
            selectFirstValue: n.actionType,
            selectSecondValue: n.propertyTypeId,
            selectThirdValue: n.acitonCodeId,
            propList: [],
            id: n.id,
            deleteFlag: n.deleteFlag,
            eqptIdList: n.eqptIdList || [],
            eqptTypeId: n.eqptTypeId,
            actionMonitorList: [],
            alarmEqptList: this.allAlarmEqptList.filter(f => f.eqptTypeId === n.eqptTypeId)
          }))
          if (monitorList?.length) {
            newData.map(n => {
              monitorList.forEach(c => {
                if (n.selectSecondValue === c.id && c.propList?.length && n.selectFirstValue !== 3) {
                  n.propList = c.propList
                  n.selectThirdValue = n.selectThirdValue ? Number(n.selectThirdValue) : n.selectThirdValue
                }
              })
            })
          }
          return {
            alarmConditionActionList: newData,
            actionMonitorList: monitorList
          }
        } else {
          return {
            alarmConditionActionList: [{ selectFirstValue: null, selectSecondValue: null, selectThirdValue: null, eqptTypeId: null, eqptIdList: [], actionMonitorList: [], alarmEqptList: [], propList: [] }],
            actionMonitorList: monitorList
          }
        }
      }
    },
    setPageWorkOrderPageParams (params) {
      // 处理页面所需格式 告警触发动作 - 工单
      const { frozenTerm, frozenTermSuffix, triggerRecieverType, contactPersons, ordersLevel, ordersTypeNo, triggerActionType } = params
      if (triggerActionType === 0) {
        // 仅告警
        return {
          frozenTerm,
          frozenTermSuffix
        }
      } else if (triggerActionType === 1) {
        // 告警并推送
        return {
          frozenTerm,
          frozenTermSuffix,
          triggerRecieverType,
          personsList: triggerRecieverType === 0 && contactPersons?.length ? contactPersons.split(',') : [],
          rolesList: triggerRecieverType === 1 && contactPersons?.length ? contactPersons.split(',') : [],
          departsList: triggerRecieverType === 2 && contactPersons?.length ? contactPersons.split(',') : []
        }
      } else {
        return {
          frozenTerm,
          frozenTermSuffix,
          triggerRecieverType,
          personsList: triggerRecieverType === 0 && contactPersons?.length ? contactPersons.split(',') : [],
          rolesList: triggerRecieverType === 1 && contactPersons?.length ? contactPersons.split(',') : [],
          departsList: triggerRecieverType === 2 && contactPersons?.length ? contactPersons.split(',') : [],
          ordersLevel: Number(ordersLevel),
          ordersTypeNo: ordersTypeNo
        }
      }
    },
    handleAlarmParams () {
      /**
       * 入参处理
       * @return 返回无
       */
      this.modalForm.alarmPlanEqptList = this.alarmPlanEqptList
      if (this.modalForm?.alarmEqptList?.length && this.modalForm.alarmPlanEqptList?.length) {
        // 临时存储deleteflag为0的数据 处理重复数据
        const tempList = this.modalForm.alarmPlanEqptList.map(n => {
          if (n.id && n.deleteFlag === 0) {
            return n.eqptId
          }
        })
        this.modalForm.alarmPlanEqptList = this.modalForm.alarmPlanEqptList.filter(n => (!tempList.includes(n.eqptId)) || (tempList.includes(n.eqptId) && n.deleteFlag === 0) || (tempList.includes(n.eqptId) && n.deleteFlag === 1))
      }
      delete this.modalForm.alarmEqptList
      if (this.shareData.title === '编辑自定义告警') {
        delete this.modalForm.eqptTypeName
      }
    },
    setConditionActionList (optionObj, alarmLevel) {
      /**
       * 处理告警触发条件或联动动作数据转换成入参所需格式
       * @params optionObj: 初级/中级/高级对象值
       *  @params alarmLevel：告警等级 - 0, 1, 2
       * @return 返回data
       */
      const { conditionTriggerFrequencyType, conditionTriggerLinkageType, contentTemplate, triggerActionType, triggerAction } = optionObj
      const data = []
      const contactPersons = triggerAction?.triggerRecieverType === 0 ? triggerAction.personsList : triggerAction?.triggerRecieverType === 1 ? triggerAction.rolesList : triggerAction.departsList
      const commonParams = {
        alarmPlanConditionList: [...this.handleConditionActionData('告警触发条件', optionObj.conditionObj.alarmConditionActionList)],
        alarmPlanTrigActionList: optionObj.actionObj?.alarmConditionActionList?.length ? [...this.handleConditionActionData('告警联动动作', optionObj.actionObj.alarmConditionActionList)] : [],
        alarmLevel,
        conditionTriggerFrequencyType,
        conditionTriggerLinkageType,
        contentTemplate,
        triggerActionType,
        contactPersons: contactPersons?.join(','),
        triggerRecieverType: triggerAction.triggerRecieverType,
        ordersLevel: triggerAction.ordersLevel,
        ordersTypeNo: triggerAction.ordersTypeNo,
        frozenTerm: Number(triggerAction.frozenTerm),
        frozenTermSuffix: triggerAction.frozenTermSuffix,
        ...this.triggerTimeObj
      }
      if (this.shareData.title === '新增自定义告警') {
        data.push({
          ...commonParams
        })
      } else {
        // 编辑状态下判断id和删除标志deleteFlag是否存在入参上送不同
        if (optionObj.id) {
          data.push({
            ...commonParams,
            id: optionObj.id,
            deleteFlag: optionObj.deleteFlag
          })
        } else {
          data.push({
            ...commonParams
          })
        }
      }
      return data
    },
    setTriggerTimeParams (optionObj) {
      /**
       * 处理告警触发时间数据转换成入参所需格式
       * @params optionObj: 初级/中级/高级对象值
       * @return 无
       */
      const { triggerTime, triggerPeriodType } = optionObj
      this.triggerTimeObj.triggerPeriodType = triggerPeriodType
      this.triggerTimeObj.triggerTimeType = triggerTime.triggerTimeType
      this.triggerTimeObj.triggerTimeValues =
          triggerTime.triggerTimeType === 0 ? triggerTime.triggerTimePointValues.map(n => n.timeValue).join(',') : triggerTime.triggerTimeRangeValues.map(n => n.timeValue.join('~')).join(',')
      if (triggerPeriodType === 0) {
        // 单次上送参数
        this.triggerTimeObj.triggerAssignDate = triggerTime.triggerAssignDate
      } else if (triggerPeriodType === 1) {
        // 每天
        this.triggerTimeObj.triggerStartDate = triggerTime.triggerStartDate
        this.setTriggerTimeEndDate(triggerTime)
      } else if (triggerPeriodType === 2) {
        // 每周
        this.triggerTimeObj.triggerStartDate = triggerTime.triggerStartDate
        this.triggerTimeObj.triggerAssignDate = triggerTime.triggerWeekAssignDate.join(',')
        this.setTriggerTimeEndDate(triggerTime)
      } else if (triggerPeriodType === 3) {
        // 每月
        this.triggerTimeObj.triggerStartDate = triggerTime.triggerStartDate
        this.triggerTimeObj.triggerAssignDate = triggerTime.triggerMonthAssignDate.join(',')
        this.setTriggerTimeEndDate(triggerTime)
      }
    },
    setTriggerTimeEndDate (triggerTime) {
      if (triggerTime.triggerEndDateType === 1) {
        this.triggerTimeObj.triggerEndDate = triggerTime.triggerEndDate
      } else {
        delete this.triggerTimeObj.triggerEndDate
      }
      this.triggerTimeObj.triggerEndDateType = triggerTime.triggerEndDateType
    },
    setAlarmPlanEqptData (params) {
      // 处理告警设备选中数据，返回入参所需格式
      const typeParams = []
      params.forEach(n => {
        this.alarmEqptList.forEach(a => {
          if (n === a.eqptId) {
            typeParams.push({
              eqptId: a.eqptId,
              eqptName: a.eqptName,
              eqptTypeId: a.eqptTypeId,
              sourceId: a.sourceId
            })
          }
        })
      })
      return typeParams
    },
    handleConditionActionData (type, data) {
      // 处理数据转换 =》入参形式
      if (this.shareData.title === '新增自定义告警') {
        if (type === '告警触发条件') {
          return data.map(n => ({
            eqptMessageParamId: n.selectFirstValue,
            alarmConditionId: n.selectSecondValue,
            threshold: n.selectThirdValue
          }))
        } else if (type === '告警联动动作') {
          return data.map(n => ({
            actionType: n.selectFirstValue,
            propertyTypeId: n.selectSecondValue,
            acitonCodeId: n.selectThirdValue,
            eqptIdList: n.eqptIdList,
            eqptTypeId: n.selectFirstValue === 3 ? n.eqptTypeId : (!n.selectFirstValue && n.selectFirstValue !== 0) ? null : this.modalForm.eqptTypeId
          }))
        }
      } else {
        if (type === '告警触发条件') {
          return data.map(n => {
            if (n.id) {
              return {
                eqptMessageParamId: n.selectFirstValue,
                alarmConditionId: n.selectSecondValue,
                threshold: n.selectThirdValue,
                id: n.id,
                deleteFlag: n.deleteFlag
              }
            } else {
              return {
                eqptMessageParamId: n.selectFirstValue,
                alarmConditionId: n.selectSecondValue,
                threshold: n.selectThirdValue
              }
            }
          })
        } else if (type === '告警联动动作') {
          const newData = data.map(n => {
            if (n.id) {
              return {
                actionType: n.selectFirstValue,
                propertyTypeId: n.selectSecondValue,
                acitonCodeId: n.selectThirdValue,
                eqptIdList: n.eqptIdList,
                eqptTypeId: n.selectFirstValue === 3 ? n.eqptTypeId : (!n.selectFirstValue && n.selectFirstValue !== 0) ? null : this.modalForm.eqptTypeId,
                id: n.id,
                deleteFlag: n.deleteFlag
              }
            } else {
              return {
                actionType: n.selectFirstValue,
                propertyTypeId: n.selectSecondValue,
                acitonCodeId: n.selectThirdValue,
                eqptIdList: n.eqptIdList,
                eqptTypeId: n.selectFirstValue === 3 ? n.eqptTypeId : (!n.selectFirstValue && n.selectFirstValue !== 0) ? null : this.modalForm.eqptTypeId
              }
            }
          })
          newData.forEach((n) => {
            if (
              n.id &&
              !n.selectFirstValue &&
              n.selectFirstValue !== 0 &&
              !n.selectSecondValue &&
              !n.selectThirdValue &&
              !n.eqptTypeId &&
              !n.eqptIdList.length
            ) n.deleteFlag = 1
          })
          return newData.filter(n => n.actionType || n.propertyTypeId || n.acitonCodeId || n.eqptIdList.length || n.eqptTypeId || n.id)
        }
      }
    },
    async getWorkTypeList () {
      // 获取工单类型列表
      try {
        const res = await getWorkTypeList(this.$ls.get(USER_INFO).tenantNo)
        if (res.code === 0) {
          this.workTypeList = res.data
        }
      } catch (e) {}
    }
  },
  mounted () {
    const { title } = this.shareData
    this.getWorkTypeList()
    this.getAllAlarmEqptList()
    if (title === '新增自定义告警') {
      this.alarmJunior = 0
    }
  }
}
</script>
<style lang="scss" scoped>
.footer {
  text-align: center;
  margin: 20px 0;
}
.el-col {
  .el-form-item {
    margin-bottom: 10px;
    ::v-deep {
      .el-form-item__error {
        padding-top: 0px;
      }
    }
  }
}
</style>
